<?php
/**
 * @brief Functions file.
 *
 * @license		http://www.gnu.org/licenses/gpl-3.0.txt GNU General Public License
 * @copyright	2007 David Singer
 * @author		David Singer <david@ramaboo.com>
 * @version		1.0.0
 */

/**
 * @brief Sets the headers correctly for no cache pages.
 * @return void.
 * @param int $content_length [optional] The content length.
 * @param string $content_type [optional] The content type.
 * @param string $charset [optional] The character set.
 */
function header_no_cache($content_length = -1, $content_type = 'text/html', $charset = 'utf-8') {
	// check if content length is a positive integer or 0
	if (ctype_digit((string) $content_length)) {
		header('Content-Length: ' . $content_length);
	}
	
	if ($content_type) {
		header("Content-Type: {$content_type}; charset={$charset}");
	}
	
	header('Expires: Mon, 26 Jul 1997 05:00:00');
	header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
	header('Cache-Control: no-store, no-cache, must-revalidate'); // HTTP/1.1
	header('Pragma: no-cache'); // HTTP/1.0
}

function require_login() {
	$auth = (isset($_SESSION['auth'])) ? $_SESSION['auth'] : false;
	
	if (!$auth) {
		header('Location: ' . BASE_URL . 'login.php');
		exit;
	}
}

// write a line to LOG_FILE
function write_log($content) {
	if (LOG_FILE) {
		if (is_array($content)) {
			// convert to string
			$content = implode(',',$content) . "\n";
		} else {
			$content = trim($content) . "\n";
		}
		
		if (is_writable(LOG_FILE)) {
			if (!$handle = fopen(LOG_FILE, 'a')) {
				throw new Exception('Cannot open LOG_FILE, check permissions on ' . LOG_FILE);
			}
			
			if (fwrite($handle, $content) === false) {
				throw new Exception('Cannot write to LOG_FILE, check permissions on ' . LOG_FILE);
			}
			fclose($handle);
		} else {
			throw new Exception('Error LOG_FILE is not writable, check permissions on ' . LOG_FILE);
		}
	}
}

function get_uptime() {
	// set handle
	$handle = fopen('/proc/uptime', 'r');
	
	if(!$handle) {
		$uptime = false;
	} else {
		// open handle
		$proc = fgets($handle);
		// close handle
		fclose($handle);
		
		// remove idle time and fractions of a second
		$result = round(substr($proc,0,strpos($proc,' ')));
		
		// divide up result
		$parts['day'] = floor($result / 86400);
		$parts['hour'] = floor(($result - ($parts['day'] * 86400)) / 3600);
		$parts['minute'] = floor(($result - ($parts['day'] * 86400) - ($parts['hour'] * 3600)) / 60);
		$parts['second'] = floor($result - ($parts['minute'] * 60) - ($parts['day'] * 86400) - ($parts['hour'] * 3600));
		
		// format uptime for output in format D HH:MM:SS or HH:MM:SS if day is 0
		$uptime = '';
		if ($parts['day']) {
			$uptime .=  $parts['day'] . ' ';
		}
		$uptime .= sprintf('%02d', $parts['hour']) . ':' . sprintf('%02d', $parts['minute']) . ':' . sprintf('%02d', $parts['second']);
	}
	
	return $uptime;
}

function redirect($url) {
	header("Location: $url");
	exit;
}

?>